﻿namespace DynaBoard
{

    /// <summary>Represents a trimmed string that is null if empty.</summary>
    public class text
    {
        /// <summary>
        /// The trimmed value of the string from which this instance was created.
        /// </summary>
        private readonly string value;

        /// <summary>Instantiate a new text.</summary>
        /// <param name="text">The string to parse.</param>
        public text(string text)
        {
            // this.value = null if it's empty, or 'text' trimmed otherwise

            this.value = (text != null && (text = text.Trim()).Length == 0) ? null : text;
        }

        public int Length
        {
            get { return this.value.Length; }
        }

        public static implicit operator string(text s)
        {
            return (s == null) ? null : s.value;
        }

        public static implicit operator text(string s)
        {
            return new text(s);
        }

        public static bool operator !(text s)
        {
            return (s == null);
        }

        public static bool operator ==(text left, object right)
        {
            bool leftIsNull = left.Equals(null);

            // If both are null, they're equal

            if ((leftIsNull || left.value == null) && right == null)
            {
                return true;
            }

            // If left.value is the same as right

            if (!leftIsNull && left.value == right as string)
            {
                return true;
            }

            // If right is a text instance and they are equal

            if (!leftIsNull && right is text && left.value == (right as text).value)
            {
                return true;
            }

            // Otherwise, they're not

            return false;
        }

        public static bool operator !=(text left, object right)
        {
            return !(left == right);
        }

    }

}